package com.zipsted.proto;

import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.*;

/**
 * Created by zipSTED LLC.
 * User: edgar
 * Date: 13.10.11
 * Time: 10:41
 */
public class Simulation extends Renderer implements Runnable {

  private boolean isSimulating = true;


  private static final float TIME_STEP = 1.0f / 1000.0f;
  private static final int VELOCITY_ITERATIONS = 6;
  private static final int POSITION_ITERATIONS = 2;

  private final Body body;

  public Simulation() {
    // ------------------------------------
    // --------   JBox2D part   -----------
    // --------     begin       -----------
    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.position.set(0.0f, -10.0f);

    Body groundBody = WORLD.createBody(groundBodyDef);

    PolygonShape groundBox = new PolygonShape();
    groundBox.setAsBox(50.0f, 10.0f);

    groundBody.createFixture(groundBox, 0.0f);
    // ------------------------------------

    BodyDef dynamicBodyDef = new BodyDef();
    dynamicBodyDef.type = BodyType.DYNAMIC;
    dynamicBodyDef.position.set(0.0f, 4.0f);
    body = WORLD.createBody(dynamicBodyDef);

    PolygonShape dynamicBox = new PolygonShape();
    dynamicBox.setAsBox(1.0f, 1.0f);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = dynamicBox;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.3f;

    body.createFixture(fixtureDef);
    // --------     end of      -----------
    // --------   JBox2D part   -----------
    // ------------------------------------
  }

  @Override
  public void run() {
    while (isSimulating) {
      WORLD.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);

      Vec2 position = body.getPosition();
      float angle = body.getAngle();
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      }
      System.out.println(position.x + " " + position.y + " " + angle);
      // TODO: -------------------------------
    }
  }

  public void stopSimulating() {
    isSimulating = false;
  }
}
